package org.example;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TouchpadHandler extends TextWebSocketHandler {

    private Robot robot;
    private boolean leftButtonDown = false;
    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    private static final int MAX_MOVE_DELTA = 20;

    public TouchpadHandler() {
        try {
            robot = new Robot();
            robot.setAutoDelay(10);
        } catch (AWTException e) {
            throw new RuntimeException("初始化失败: " + e.getMessage());
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        final String payload = message.getPayload();
        executor.submit(() -> {
            try {
                if (payload.startsWith("MOVE:")) {
                    handleMove(payload.substring(5));
                } else if ("LEFT_CLICK".equals(payload)) {
                    handleClick(InputEvent.BUTTON1_DOWN_MASK);
                } else if ("RIGHT_CLICK".equals(payload)) {
                    handleClick(InputEvent.BUTTON3_DOWN_MASK);
                } else if (payload.startsWith("SCROLL:")) {
                    handleScroll(payload.substring(7));
                } else if ("LEFT_DOWN".equals(payload)) {
                    handleLeftDown();
                } else if ("LEFT_UP".equals(payload)) {
                    handleLeftUp();
                } else if ("COPY".equals(payload)) {
                    handleCopy();
                } else if ("PASTE".equals(payload)) {
                    handlePaste();
                } else {
                    // 这里减少打印，避免性能影响
                }
            } catch (Exception e) {
                System.err.println("处理错误: " + e.getMessage());
                e.printStackTrace();
            }
        });
    }

    private void handleMove(String data) {
        String[] coords = data.split(",");
        int dx = (int) Float.parseFloat(coords[0]);
        int dy = (int) Float.parseFloat(coords[1]);

        // 限制最大移动距离，防止跳跃
      /*  dx = Math.max(-MAX_MOVE_DELTA, Math.min(MAX_MOVE_DELTA, dx));
        dy = Math.max(-MAX_MOVE_DELTA, Math.min(MAX_MOVE_DELTA, dy));*/

        PointerInfo pi = MouseInfo.getPointerInfo();
        if (pi == null) {
            System.err.println("无法获取鼠标位置");
            return;
        }
        Point p = pi.getLocation();
        int newX = p.x + dx;
        int newY = p.y + dy;
        robot.mouseMove(newX, newY);
    }

    private void handleClick(int button) {
        robot.mousePress(button);
        robot.mouseRelease(button);
    }

    private void handleScroll(String data) {
        float delta = Float.parseFloat(data);
        int wheelAmt = (int) (delta / 15);
        if (wheelAmt != 0) {
            robot.mouseWheel(wheelAmt);
        }
    }

    private void handleLeftDown() {
        if (!leftButtonDown) {
            robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            leftButtonDown = true;
        }
    }

    private void handleLeftUp() {
        if (leftButtonDown) {
            robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
            leftButtonDown = false;
        }
    }

    private void handleCopy() {
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_C);
        robot.keyRelease(KeyEvent.VK_C);
        robot.keyRelease(KeyEvent.VK_CONTROL);
    }

    private void handlePaste() {
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
    }

    public void shutdown() {
        executor.shutdown();
    }
}
